package spring.lottery.common.util;

import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MailUtil {

    @Value(value = "${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    public Boolean sendSampleMail(String to, String tile, String context) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(tile);
        message.setText(context);

        if(!"tangdeyx2333@163.com".equals(to)) {
            log.error("取消发送 {}", to);
        }

        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error("向{}发送邮件失败！", to, e);
            return false;
        }
        return true;
    }

    public Boolean sendHtmlMail(String to, String subject, String htmlContent) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); // 关键：设置为true
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);

            if(!"tangdeyx2333@163.com".equals(to)) {
                log.error("取消发送 {}", to);
                throw new Exception();
            }

            mailSender.send(message);

        } catch (Exception e) {
            log.error("向{}发送邮件失败！", to, e);
            return false;

        }
        return true;
    }

}
